import { _decorator, Component, Node, UITransform, view, screen } from "cc";
const { ccclass, property } = _decorator;

/**
 * 需要勾选适配屏幕宽和高
 */
@ccclass("FullBg")
export class FullBg extends Component {
  // 设计分辨率
  private _dSize = view.getDesignResolutionSize();

  protected onLoad(): void {
    this._filtAll();
    this._fullBg();
  }

  /**
   * 背景全屏
   */
  private _fullBg() {
    const uiTransform = this.getComponent(UITransform);

    // 节点尺寸
    const contentSize = uiTransform.contentSize;

    const sW = screen.windowSize.width / contentSize.width;
    const sH = screen.windowSize.height / contentSize.height;

    const scaleForShowAll = Math.min(sW, sH);

    let realWidth = contentSize.width * scaleForShowAll;
    let realHeight = contentSize.height * scaleForShowAll;

    const scale = Math.max(
      screen.windowSize.width / realWidth,
      screen.windowSize.height / realHeight
    );
    // 使用缩放的方式
    // this.node.setScale(scale, scale);
    // 或是设置尺寸
    uiTransform.setContentSize(
      contentSize.width * scale,
      contentSize.height * scale
    );
  }

  /**
   * 先给元素做个简单的适配，就是设置元素的宽或者高刚好等于屏幕的宽或者高，方便后面计算
   * 但是这么设置呢，这玩意有点麻烦，分4种情况，用图画一下就明白了
   */
  private _filtAll() {
    // 设计分辨率的宽大于高的时候
    if (this._dSize.width > this._dSize.height) {
      // 假如设计分辨率的宽高比大于元素的宽高比
      if (this._isDesignGtUI()) {
        // 元素的高度等于屏幕的高度，宽度等比例缩放
        this._filtHeight();
      } else {
        // 元素的宽度等于屏幕的宽度，高度等比例缩放
        this._filtWidth();
      }
    } else {
      // 假如设计分辨率的宽高比大于元素的宽高比
      if (this._isDesignGtUI()) {
        // 元素的宽度等于屏幕的宽度，高度等比例缩放
        this._filtWidth();
      } else {
        // 元素的高度等于屏幕的高度，宽度等比例缩放
        this._filtHeight();
      }
    }
  }

  /**
   * 适配高度
   * 元素的高度等于屏幕的高度，宽度等比例缩放
   */
  private _filtHeight() {
    const uiTransform = this.getComponent(UITransform);
    const scale = this._dSize.height / uiTransform.height;
    uiTransform.setContentSize(
      uiTransform.width * scale,
      uiTransform.height * scale
    );
  }

  /**
   * 适配宽度
   * 元素的宽度等于屏幕的宽度，高度等比例缩放
   */
  private _filtWidth() {
    const uiTransform = this.getComponent(UITransform);
    const scale = this._dSize.width / uiTransform.width;
    uiTransform.setContentSize(
      uiTransform.width * scale,
      uiTransform.height * scale
    );
  }

  /**
   * 设计分辨率的宽高比大于元素的宽高比
   * @returns {boolean}
   */
  private _isDesignGtUI(): boolean {
    const uiTransform = this.getComponent(UITransform);
    return (
      this._dSize.width / this._dSize.height >
      uiTransform.width / uiTransform.height
    );
  }
}
